package br.uff.gdse.positionevaluation.evaluators;

import java.util.ArrayList;
import java.util.List;

import org.exist.xmldb.EXistResource;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XPathQueryService;

import br.uff.gdse.positionevaluation.queries.XMLQuery;
import br.uff.gdse.positionevaluation.util.DBUtil;

public class XIndiceInterface implements IDBInterface {

	private static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
	
    /**
     * args[0] Should be the name of the collection to access
     * args[1] Should be the XPath expression to execute
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     * @throws ClassNotFoundException 
     * @throws XMLDBException 
     */
   
	@Override
	public List<Object> executeQuery(XMLQuery query){
		final String driver = "org.exist.xmldb.DatabaseImpl";
        Collection col = null;
        List<Object> result = new ArrayList<Object>();
        Database database = null;
        
        try { 
        	database = DBUtil.registerDabatase(driver); 
            col = DatabaseManager.getCollection(URI + query.getCollection());
            XPathQueryService xpqs = (XPathQueryService)col.getService("XPathQueryService", "1.0");
            xpqs.setProperty("indent", "yes");

            ResourceSet resourceSet = xpqs.query(query.getQuery());
            ResourceIterator i = resourceSet.getIterator();
            Resource res = null;
            while(i.hasMoreResources()) {
                try {
                    res = i.nextResource();
                    result.add(res);
                    System.out.println(res.getContent());
                } finally {
                    try { ((EXistResource)res).freeResources(); } catch(XMLDBException xe) {xe.printStackTrace();}
                }
            }
        } catch (Exception e) {
			e.printStackTrace();
		} finally {
            if(col != null) {
                try { col.close(); } catch(XMLDBException xe) {xe.printStackTrace();}
            }
            try { DatabaseManager.deregisterDatabase(database);	} catch (XMLDBException e) { e.printStackTrace();}
        }
        
        return result;
	}

}
